package com.hong.config;

import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig  implements WebMvcConfigurer {

    public static final String TOKEN_HEADER = "Authorization";

    /**
     * groupName() 定义组名（根据自己需求定义名称）
     * apiInfo(apiInfo()) 指定文档标题和版本号
     * useDefaultResponseMessages()  启用默认响应消息
     * select()  选择要生成文档的接口
     * apis(RequestHandlerSelectors.basePackage()  指定要生成生成文档的接口的包路径
     * apis(RequestHandlerSelectors.withClassAnnotation()) 扫描被@RestController注解标记的类，生成文档
     * paths(PathSelectors.any())  包含在文档中的接口路径
     * build()  建 Docket 对象
     *
     * @return  Docket 对象
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("测试案例")
                .apiInfo(apiInfo("SpringBoot集成Swagger", "1.0.0"))
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false) //是否生成代码 否
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                ////设置全局token
                .securitySchemes(security())
                .securityContexts(securityContexts());
                //每个接口传token
//                .globalRequestParameters(globalRequestParameters());
    }
    /**
     * 使用 Springfox 生成 Swagger 文档时，用来设置 API 文档的基本信息的
     * 访问地址：http://ip:port/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo(String title, String version) {
        return new ApiInfoBuilder()
                .title(title)
                .description("更多请关注: https://swagger.io/")
                .version(version)
                .build();
    }


    private List<SecurityScheme> security() {
        List<SecurityScheme> apiKeys = new ArrayList<>();
        ApiKey header = new ApiKey(TOKEN_HEADER, TOKEN_HEADER, In.HEADER.toValue());
        apiKeys.add(header);

        return apiKeys;
    }
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts=new ArrayList<>();
        securityContexts.add(
                SecurityContext
                        .builder()
                        .securityReferences(securityReferences())
                        .operationSelector(operationContext ->operationContext.requestMappingPattern().startsWith("/"))
                        .build());
        return securityContexts;
    }

    private List<SecurityReference> securityReferences() {
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[] {new AuthorizationScope("global", "accessEverything")};
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference(TOKEN_HEADER, authorizationScopes));
        return securityReferences;
    }

    /**
     * 每个接口传token
     * @return
     */
    private List<RequestParameter> globalRequestParameters() {
        return Arrays.asList(new RequestParameterBuilder()
                .name(TOKEN_HEADER)
                .description("access token")
                .in(ParameterType.HEADER)
                .required(false)
                .build());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决swagger⽆法访问
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        // 解决swagger的js⽂件⽆法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 解决swagger无法访问
//        registry.addResourceHandler("/swagger-ui.html")
//                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
//        registry.addResourceHandler("/webjars/**")
//                .addResourceLocations("classpath:/META-INF/resources/webjars/");
//        registry.addResourceHandler("doc.html")
//                .addResourceLocations("classpath:/META-INF/resources/");

    }
}



